import Request from './request'
import apiList from './api.js'

export default function api(url, data = {}, showToast = true) {
	const request = new Request();
	let api = getApiObj(url);
	// console.log(api,'api')
	request.interceptor.request((config, cancel) => {
		/* 请求之前拦截器 */
		if (api.auth) {
			let token = uni.getStorageSync('token');
			// console.log(token,'token',!token)
			if (!token) {
				uni.showModal({
					title: '提示',
					content: '您还没有登录，是否进行授权登录？',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index', //授权页面
							})
						} else if (res.cancel) {
							uni.showModal({
								title: '温馨提示',
								content: '拒绝后将会对您的功能体验有部分影响',
								confirmText: "知道了",
								showCancel: false,
								success: function(res) {
									///点击知道了的后续操作
									///如跳转首页面
									uni.navigateTo({
										url: '/pages/index/index', //跳转到首页
									})
								}
							});
						}
					}
				});
			}
		}
		if (uni.getStorageSync('token')) {
			config.header['Authorization'] = uni.getStorageSync('token');
		}
		return config
	});
 
	request.interceptor.response((response) => {
		/* 请求之后拦截器 */
		if (response.data.code === 0) { // 服务端返回的状态码不等于200，则reject()
			if (showToast) {
				uni.showToast({
					title: response.data.msg || '请求出错,稍后重试',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}
		}
		if (response.data.code === 401) { // 服务端返回的状态码不等于200，则reject()
			uni.removeStorageSync('token');
		}

		// if (response.config.custom.verification) { // 演示自定义参数的作用
		//   return response.data
		// }
		return response
	}, (response) => { // 预留可以日志上报
		return response
	})
	if (api.host) {
		let params = uni.$u.queryParams(data);
		return request.request({
			url: api.url + params,
			method: api.method
		})
	} else {
		return request.request({
			url: api.url,
			data,
			method: api.method
		})
	}
 
}
 
function getApiObj(url) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}